﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Build.Framework;
using System.Reflection;

namespace MSBuild.DotNetNuke.Tasks
{
	/// <summary>
	/// Creates/replaces the assembly component in the manifest file based on the list of files
	/// passed.
	/// </summary>
	public class AssemblyComponent : Component
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="AssemblyComponent"/> class.
		/// </summary>
		public AssemblyComponent()
		{
			_type = ComponentType.Assembly;
		}


		protected override string GetContainerElement()
		{
			return "assemblies";
		}

		protected override void WriteItemElement(XmlWriter output, ITaskItem item)
		{
			string assemblyName = System.IO.Path.GetFileName(item.ItemSpec);

			output.WriteStartElement("assembly");

			if (!string.IsNullOrEmpty(Path))
			{
				output.WriteElementString("path", Path);
			}
			output.WriteElementString("name", assemblyName);

			try
			{
				Version version = System.Reflection.AssemblyName.GetAssemblyName(item.ItemSpec).Version;
				output.WriteElementString("version", version.ToString(3));
			}
			catch (Exception ex)
			{
				Log.LogMessage(MessageImportance.Normal, "Cannot determine version for assembly: " + assemblyName + ". " + ex.Message);
			}

			output.WriteEndElement(); // </assembly>
			Log.LogMessage(MessageImportance.Low, string.Format("Assembly: {0}", assemblyName));
		}
	}
}
